﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Extensil.Common;
using System.IO;
using System.Reflection;
using Extensil.Processor.Extensibility;
using System.Windows.Forms;


namespace TaskAutomation.General
{
    public class TaskFactory
    {
        public static TaskBase GetTaskHandler(string handler)
        {
            TaskBase retValue;
            switch(handler.ToLower())
            {

                case "batchprocess":
                    retValue = new BatchProcess();
                    break;
                default:
                    TaskReader tr = new TaskReader();
                    HandlerList hList = tr.HandlerList;
                    Handler hnd = hList[handler];
                    if(hnd == null)
                        throw new Exception("Handler " + handler + " is not registered.");

                    string path = hnd.Path;
                    string[] hndClass = path.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                    if(!File.Exists(Application.StartupPath + "/" + hndClass[1].Trim() + ".dll"))
                        throw new Exception("Handler " + hndClass[1].Trim() + ".dll could not be found.");

                    Assembly asm = PluginAssembly.Load(Application.StartupPath + "/" + hndClass[1].Trim() + ".dll");
                    retValue = (TaskBase)asm.CreateInstance(hndClass[0].Trim());
                    break;
            }
            return retValue;
        }
        public static List<string> GetSystemTaskHandlers()
        {
            return (from t in Assembly.GetExecutingAssembly().GetTypes()
                    where t.BaseType == (typeof(TaskBase)) && t.GetConstructor(Type.EmptyTypes) != null
                    select t.Name).ToList();
        }
    }
}
